package com.sd365.permission.centre.api.controller;

import cn.hutool.http.HttpStatus;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.permission.centre.api.LoginApi;
import com.sd365.permission.centre.entity.Role;
import com.sd365.permission.centre.entity.User;
import com.sd365.permission.centre.pojo.dto.CompanyDTO;
import com.sd365.permission.centre.pojo.vo.ResourceVO;
import com.sd365.permission.centre.service.CompanyService;
import com.sd365.permission.centre.service.LoginService;
import com.sd365.permission.centre.service.UserOnlineService;
import com.sd365.permission.centre.service.util.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * @description: 退出登录修复
 * @author: wujiandong
 * @create: 2022/8/5 17:15
 * @version: v1.0.9
 **/
@RestController
@Slf4j
@Validated
public class LoginController  implements LoginApi {

    /**
     * 登录服务
     */
    @Resource
    private LoginService loginService;
    /**
     * 公司服务
     */
    @Resource
    private CompanyService companyService;
    /**
     * 用户在线服务
     */
    @Resource
    private UserOnlineService userOnlineService;
    /**
     * 需要从缓存读取
     */
    @Resource
    private RedisTemplate redisTemplate;
    /**
     * redis缓存的token key
     */
    private static final String USER_TOKEN_KEY = "user:token:";
    /**
     * redis缓存的i用户登录信息 key
     */
    private static final String USER_LOGING_KEY = "user:loginInfo:";

    @Override
    public UserVO auth(@RequestParam(value = "code")  String code, @RequestParam(value = "password")  String password, @RequestParam(value = "account")  String account) {
        /**
         * 1 认证通过返回带权限的UserVO
         * 2 插入登录记录并且更新登录状态
         */
        UserVO userVO = new UserVO();

        LoginService.LoginUserDTO loginUserDTO = loginService.auth(code, password, account);
        log.debug("UserDTO的结果码为"+loginUserDTO.getResultCode());
         switch (loginUserDTO.getResultCode())  {
            case LoginService.LOGIN_VERIFY_CODE_TENANT_ERR:
                userVO.setCode(HttpStatus.HTTP_UNAUTHORIZED);
                userVO.setMsg("账号和租户不匹配或不存在");
                break;
             case LoginService.LOGIN_VERIFY_CODE_SUCCESS:
                 ResponseData responseData = new ResponseData();
                 responseData.setToken("");
                 // token 在认证服务生成
                 responseData.setName(loginUserDTO.getName());
                 userVO.setId(loginUserDTO.getId());
                 // 应答信息
                 userVO.setData(responseData);
                 userVO.setRoleIds(loginUserDTO.getRoleIds());
                 userVO.setTenantId(loginUserDTO.getTenantId());
                 userVO.setOrgId(loginUserDTO.getOrgId());
                 userVO.setCompanyId(loginUserDTO.getCompanyId());
                 userVO.setCode(HttpStatus.HTTP_OK);
                 userVO.setMsg("登录成功");
                 break;
             case LoginService.LOGIN_VERIFY_CODE_CODE_OR_PASSWORD_ERR:
                 userVO.setCode(HttpStatus.HTTP_UNAUTHORIZED);
                 userVO.setMsg("用户名或密码错误，登录失败");
                 break;
             default:
        }
        return userVO;
    }



    @Override
    public UserVO login( @RequestParam(value = "code") String code,
                         @RequestParam(value = "password") String password,
                         @RequestParam(value = "account") String account) {
        // 根据user.code, user.password, tenant.account
        UserVO userVO = new UserVO();

        userVO.data = new ResponseData();

        int flag = loginService.verification(code, Md5Utils.digestHex(password), account);

        if (flag == 1) {

            userVO.data.setToken("1");
            userVO.setCode(200);
            userVO.setMsg("登录成功");
            User userInfo = loginService.getUserInfo(code, account);
            userVO.setId(userInfo.getId());
            userVO.setCompanyId(userInfo.getCompanyId());
            userVO.setTenantId(userInfo.getTenantId());
            userVO.setOrgId(userInfo.getOrgId());

        } else if (flag == 0) {
            userVO.setCode(401);
            userVO.setMsg("账号和租户不匹配或不存在");
        } else {
            userVO.setCode(401);
            userVO.setMsg("用户名或密码错误，登录失败");
        }
        return userVO;
    }
    @Override
    public UserVO info(@RequestParam(value = "code") String code,
                       @RequestParam(value = "account") String account) {

             // 查找对应的用户
        User user = loginService.getUserInfo(code, account);
        // 查找用户对应的角色
        List<Role> roles = loginService.getRolesByUserId(user.getId());
        List<String> rolesName = new LinkedList<>();
        for (Role role : roles) {
            rolesName.add(role.getName());
        }

        UserVO userVO = new UserVO();
        userVO.data = new ResponseData();
        if(!roles.isEmpty()){
            // 查找对应的资源ResourceVO
            List<ResourceVO> resourceVOS = loginService.getResourceVO(roles);
            userVO.data.setResourceVO(resourceVOS);
            log.debug("##resourceVOS:" + resourceVOS);
        }
        userVO.data.setAvatar(user.getProfilePicture());
        userVO.data.setRoles(rolesName);
        userVO.data.setName(user.getName());
        userVO.setCode(HttpStatus.HTTP_OK);
        userVO.setTel(user.getTel());
        userVO.setTenantId(user.getTenantId());
        userVO.setCompanyId(user.getCompanyId());
        userVO.setOrgId(user.getOrgId());
        userVO.setId(user.getId());
        userVO.setMsg("登录成功");
        User userInfo = loginService.getUserInfo(code, account);
        userVO.setId(userInfo.getId());
        CompanyDTO companyDTO = companyService.queryById(user.getCompanyId());
        userVO.setCompanyAddress(companyDTO == null ? companyDTO.getAddress() : "您的默认单位地址");
        return userVO;

    }
    @Override
    public UserVO logout() {
        String logoutId = BaseContextHolder.getUserIdStr();
        userOnlineService.forceLogout(logoutId);
        UserVO userVO = new UserVO();
        userVO.data = new ResponseData();
        userVO.setCode(HttpStatus.HTTP_OK);
        return userVO;
    }
}
